#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define KEY 6
char id[1024];
int num;
int token;
int len = 0;
void lexical(FILE *fp) {
	char x = getc(fp);
	while(x=='\t'||x==' '||x=='\t')
		x = getc(fp);
	num = 0;
	strcpy(id,"\0");
	if('0'<=x&&x<='9'){  //如果是数字
		token = 11;
		do{
			num = num*10+atoi(x);//将字符转换为整型，并将高位乘10后相加
			x = getc(fp);
		}while('0'<=x&&x<='9');
		fseek(fp,-1,SEEK_CUR);   //将指针退回最后一次getc（）之前
	}
	else if(('a'<=x&&x<='z')||('A'<=x&&x<='Z')){  //如果以字母开头
		id[0] = x;
		id[1] = '\0';
		x = getc(fp);
		while(('0'<=x&&x<='9')||('a'<=x&&x<='z')||('A'<=x&&x<='Z')){//获取标识符的内容
			len = strlen(id);
			id[len] = x;

			id[len+1] = '\0';
			x = getc(fp);
		}
		fseek(fp,-1,SEEK_CUR); 
		//strcat(id,'\0');
		if(strcmp(id,"for")==0) token = 1;// 如果是关键字
		else if(strcmp(id,"if")==0) token = 2;
		else if(strcmp(id,"then")==0) token = 3;
		else if(strcmp(id,"else")==0) token = 4;
		else if(strcmp(id,"while")==0) token = 5;
		else if(strcmp(id,"do")==0) token = 6;
		else token = 10;
		}

	else{//如果既不是字母开头，又不是数字开头
		switch(x){
			case '+':token = 13; id[0] = x; id[1] = '\0'; break;
			case '-':token = 14; id[0] = x; id[1] = '\0'; break;
			case '*':token = 15; id[0] = x; id[1] = '\0'; break;
			case '/':token = 16; id[0] = x; id[1] = '\0'; break;
			case ':':if(getc(fp)=='='){token = 18; strcpy(id,":=");}
				else{token = 17; id[0] = x; id[1] = '\0';}
				fseek(fp,-1,SEEK_CUR); 
				break;
			case '<':{
				char t = getc(fp);
				if(t=='>'){token = 21;strcpy(id,"<>");}
				else if(t=='='){token = 22; strcpy(id,"<=");}
				else{token = 20; id[0] = x; id[1] = '\0';}
				fseek(fp,-1,SEEK_CUR); 
				break;}
			case '>':if(getc(fp)=='='){token = 24; strcpy(id,">=");}
				else{token = 23; id[0] = x; id[1] = '\0';}
				fseek(fp,-1,SEEK_CUR); 
				break;
			case '=':token = 25; id[0] = x; id[1] = '\0'; break;
			case ';':token = 26; id[0] = x; id[1] = '\0'; break;
			case '(':token = 27; id[0] = x; id[1] = '\0'; break;
			case ')':token = 28; id[0] = x; id[1] = '\0'; break;
			case '#':token = 0; id[0] = x; id[1] = '\0'; break;
			default:token = -1;
			}

	//process x
	//process each regex here
	//store the result in global variables id, num, or token
	//in case of backtrack, use


	//ungetc(x, fp);
	
	}
}

int main(int argc, const char *argv[])
{

	void lexical(FILE *fp);
	if(argc < 2) {
		printf("insufficient args\n");
		return 1;
	}
	FILE *fp = fopen(argv[1], "r");
	do {
		lexical(fp);
		switch(token) {
			case 10: printf("(id, %s)\n", id); break;
			case 11: printf("(num, %d)\n", num); break;
			case -1: printf("error!\n"); break;
			default: printf("(%d, %s)\n", token, id); 		
		}
	} while(token != 0);
	


	fclose(fp);
	return 0;
}
